<template>
  <div>
    <!-- 条件查询优惠券列表 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="优惠券ID">
          <el-input
            v-model.trim="searchModel.id"
            placeholder="请输入优惠券ID"
          />
        </el-form-item>
        <el-form-item label="营销ID">
          <el-input
            v-model.trim="searchModel.templateId"
            placeholder="请输入营销ID"
          />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select
            v-model="searchModel.businessType"
            placeholder="请选择业务类型"
          >
            <el-option label="全部" :value="null" />
            <el-option label="ETC套餐销售" :value="1" />
            <el-option label="其他" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input
            v-model.trim="searchModel.userId"
            placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="使用场景">
          <el-select
            v-model="searchModel.useSceneType"
            placeholder="请选择使用场景"
          >
            <el-option label="全部" :value="null" />
            <el-option label="加油" :value="1" />
            <el-option label="洗车" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchModel.status" placeholder="请选择状态">
            <el-option label="全部" :value="null" />
            <el-option label="待使用" value="0" />
            <el-option label="已使用" value="1" />
            <el-option label="已过期" value="2" />
            <el-option label="无效" value="3" />
            <el-option label="已锁定" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用日期">
          <el-date-picker
            v-model="searchModel.useDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="业务订单号">
          <el-input
            v-model.trim="searchModel.orderId"
            placeholder="请输入业务订单号"
          />
        </el-form-item>
      </el-form>
      <div class="subBtnBox">
        <el-button type="primary" color="#ea5b24" @click="searchOrder()"
          >查询</el-button
        >
        <el-button
          type="primary"
          color="#ea5b24"
          @click="exportCoupon()"
          v-if="pinia.isShow[174]"
          >导出Excel</el-button
        >
      </div>
    </div>

    <!-- 优惠券数据列表 -->
    <div style="margin-top: 20px">
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column prop="id" width="200" label="优惠券ID" />
        <el-table-column prop="templateId" width="200" label="营销ID" />
        <el-table-column prop="businessName" label="业务类型" />
        <el-table-column prop="productName" width="110" label="适用套餐系列" />
        <el-table-column prop="userId" label="用户ID" />
        <el-table-column prop="useSceneType" label="使用场景">
          <template #default="scope">
            {{ scope.row.useSceneType == 1 ? "加油" : "洗车" }}
          </template>
        </el-table-column>
        <el-table-column prop="couponPrice" label="券面金额" />
        <el-table-column width="165" label="有效期">
          <template #default="scope">
            {{ scope.row.validityStartTime + "-" + scope.row.validityEndTime }}
          </template>
        </el-table-column>
        <el-table-column prop="useConditionStr" width="110" label="使用条件" />
        <el-table-column prop="status" :formatter="judgeState" label="状态">
          <template #default="scope">
            <div :style="{ color: judgeStateColor(scope.row) }">
              {{ judgeState(scope.row) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" width="160" label="使用日期" />
        <el-table-column prop="orderId" width="200" label="业务订单号" />
        <el-table-column fixed="right" label="操作">
          <template v-slot:default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="checkCouponStatus(scope.row)"
              v-if="scope.row.status == 0 && pinia.isShow[175]"
              >置为无效</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  findCouponListApi,
  checkCouponStatusApi,
  findCouponExcelApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 翻页
let flipData = reactive({
  pageNum: page,
  pageSize: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.pageNum = page.value;
  findCoupon(flipData);
};

// 搜索模型
const searchModel: any = reactive({
  id: null,
  templateId: null,
  businessType: null,
  userId: null,
  useSceneType: null,
  status: null,
  orderId: null,
  useDate: null,
  useStartTime: null,
  useEndTime: null,
  pageNum: page,
  pageSize: size,
});

// 过滤状态显示
function judgeState(item) {
  switch (item.status) {
    case 0:
      return "待使用";
    case 1:
      return "已使用";
    case 2:
      return "已过期";
    case 3:
      return "无效";
    case 4:
      return "已锁定";
    default:
      return "";
  }
}

// 判断状态颜色
const judgeStateColor = (row) => {
  switch (row.status) {
    case 1:
      return "#21D86E";
    case 2:
      return "red";
    case 3:
      return "#FF05D2";
    default:
      return "black";
  }
};

const searchOrder = () => {
  page.value = 1;
  if (searchModel.useDate) {
    searchModel.useStartTime = formatDateTime(searchModel.useDate[0]);
    searchModel.useEndTime = formatDateTime(searchModel.useDate[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.useStartTime = null;
    searchModel.useEndTime = null;
  }
  searchParmSearch();
  findCoupon(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};
// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

// 查询营销任务列表
const findCoupon = (searchModel) => {
  findCouponListApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.items;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 置为无效
const checkCouponStatus = (item) => {
  ElMessageBox.confirm("是否确认置为无效?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    checkCouponStatusApi({ id: item.id, status: 3 }).then((res) => {
      if (res.data.code === 2000) {
        ElMessage({
          message: "已置为无效.",
          type: "success",
        });
        findCoupon(searchModel);
      } else {
        ElMessage.error("置为无效失败.");
      }
    });
  });
};

//导出
const exportCoupon = () => {
  findCouponExcelApi(searchModel).then((res) => {
    const blob = new Blob([res.data]);
    const fileName = "优惠券列表数据.xls";
    const elink = document.createElement("a"); // 创建a标签
    elink.download = fileName; // 为a标签添加download属性
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click(); // 点击下载
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink); // 释放标签
  });
};

onMounted(() => {
  findCoupon(searchModel);
});
</script>
<style scoped>
:deep(.demo-form-inline) {
  display: grid;
  justify-items: stretch;
  grid-template-columns: repeat(auto-fill, 25%);
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item) {
  width: 90%;
}

.subBtnBox {
  width: 100%;
  margin-bottom: 20px;
  display: block;
  text-align: center;
}
</style>
